use Entity;

## --------------------------------------
## Can spawn other creatures
package Spawner;
@ISA = qw/Entity/;


sub init{
    my $self = shift;

    $self->{PIC} = '*';
    $self->dependencies(qw/EntityManager OperationManager LogManager/);
}

sub tick{
    my $self = shift;

    return if(rand(100) gt 20);

    my $map = $self->getMapsPlacedIn->[0];
    my $pos = $self->pos;

    # Spawnlings should go directly to the left of the spawner
    $pos->[0] -= 1;


    # Check if location is free
    my $op_params = {"POS"=>$pos, "MAP" =>  $map};
    my $result = $self->{OperationManager}->runOperations($op_params, qw/CheckCellOccupied/);
    return if($result->is("FAILURE"));

    # Create the new spawnling and place it
    my $spawnling = $self->{EntityManager}->spawnEntity("Spawnling", "CREATURE");
    $op_params->{"ENTITY"} = $spawnling;
    $op_params->{"CATEGORY"} = "CREATURE";
    $self->{OperationManager}->runOperations($op_params, qw/PlaceEntity/);
}

## --------------------------------------
## Spawned creature
## Pic is randomized at creation
package Spawnling;
@ISA = qw/Entity/;


sub init{
    my $self = shift;

    my @pics = ('b', 'o', 'i', 'q', 'w');
    $random = int(rand(5));
    
    $self->{PIC} = $pics[$random];
    
    $self->dependencies(qw/OperationManager EntityManager/);
}

sub tick{
    my $self = shift;

    return if(rand(100) > 50);
    my $map = $self->getMapsPlacedIn->[0];
    my $pos = $self->pos;

    $pos->[0] -= 1; # Always moving left
    $pos->[1] += $self->getRandomDisplacement() if(rand(100) gt 80); # Random up-down movement at random times
    
    my $op_params = {
	"ENTITY" => $self,
	"POS" => $pos,
	"MAP" => $map
    };
    $result = $self->{OperationManager}->runOperations($op_params,"CheckCellExists", "CheckSurvival", "CheckCellOccupied", "MoveEntity");

    if($result->is("DEAD")){
	$self->{OperationManager}->runOperations($op_params, "KillEntity");
    }
}


sub getRandomDisplacement{
    my $self = shift;
    return int(rand(3)) - 1;
}

## --------------------------------------
## Player characteer
##
package Warrior;
@ISA = qw/Entity/;

sub init{
    my $self = shift;
    $self->pic('W'); 
}

sub tick{
    my $self = shift;
}

1;
